package cn.tedu.dao;

import cn.tedu.entity.User;
import cn.tedu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {
    public User login(String username, String password) {
        try(Connection conn = DBUtils.getConn()){
            String sql = "select * from user where username=? and password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String pwd = rs.getString(3);
                return new User(id,name,pwd);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public void insert(User user) {
        try(Connection conn = DBUtils.getConn()){
            String sql = "insert into user values(null.?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String check(String username) {
        try(Connection conn = DBUtils.getConn()){
            String sql = "select * from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                return "该用户名以存在，请重新输入!";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "恭喜您，可以使用该用户名！";
    }
}
